import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  GetAllHaveSignedContractPurchaseOrdersName,
  ProductShipmentOrdersGetAllByPagedAndSort,
  ProductShipmentOrdersCreate,
  PurchaseOrdersGetInfoById,
  ProductShipmentOrdersGetShippingCode,
  ConfirmInWarehouse
} from "@/api/stu/SupplyChainFinance";
import { addres } from "@/utils/public/addres"
import { FXQ } from "@/utils/public/FXQ"
import { emitter } from "@/utils/mitt";
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted, computed } from "vue";
import qs from "qs";
export function useSupplierMaterial() {
  const route = useRoute();
  const Vdialog = ref(false);
  const receptVisible = ref(false)
  const showdialog = ref(false)
  const loading = ref(false);
  const dataList = ref([]);
  const FormDisabled = ref(true);
  const orderList = ref()
  const isSeal = ref(false) //第一个盖章
  const isAccept = ref(false)
  const isSeal1 = ref(false)
  const nextStep = ref(false)
  const selectData = ref()
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns = [
    {
      label: "序号",
      type: "index",
      minWidth: 50
    }, {
      label: "供应商",
      prop: "consigner",
    }, {
      label: "购销项目名称",
      prop: "purchaseName",
    }, {
      label: "发货单编号",
      prop: "trackingNumber",
    },
    {
      label: "收货机构名称",
      prop: "consignee",
    }, {
      label: "货物金额（元）",
      prop: "total",
    },
    {
      label: "回单确认",
      prop: "isInWarehouse",
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.isInWarehouse == 2 ? "success" : "warning"}>
          {
            row.isInWarehouse == 2 ? "已回单确认" : "未回单确认"
          }
        </el-tag>
      )
    }, {
      label: "操作",
      fixed: "right",
      minWidth: 150,
      slot: "operation"
    },
  ];
  const DispatchForm = reactive({
    trackingNumber: '',
    shipDate: '',
    adress: '',
    purchaseName: "",
    receiveName: "",
    deliverName: "",
    carrierName: "****物流公司",
    orderDate: "",
    deliveryTime: "",
    infoList: '',
    originInfoList: '',
    id: '',
    totalMoney: 0,
    totalAmountInWords: ''
  });

  function roundAddress() {
    let province = addres[Math.floor(Math.random() * addres.length)];
    let provinceName = province.province;
    if (province.city.length === 1) {
      const cityName = province.city[0].name;
      DispatchForm.adress = cityName + '市区' + '******';
    } else {
      const city = province.city[Math.floor(Math.random() * province.city.length)];
      DispatchForm.adress = provinceName + city.name + '******';
    }
  }
  function handleSizeChange() {
    getList()
  }
  function handleCurrentChange() {
    getList()
  }
  async function getList() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      SEIId: sessionStorage.getItem("seiId"),
    }
    const res = await ProductShipmentOrdersGetAllByPagedAndSort(data);
    if (res.success) {
      res.data.items.forEach(item => {
        let arr = JSON.parse(item.productInformations)
        let total = arr.reduce((acc, a) => {
          return acc + a.Price * a.Quantity
        }, 0)
        item.total = total
      })
      dataList.value = res.data.items;
      pagination.total = res.data.totalCount
    } else {
      ElMessage.error(res.msg)
    }
  }
  async function getOrderList() {
    const data = qs.stringify({
      taskId: route.query.taskId,
      planId: route.query.planId,
      sEId: sessionStorage.getItem("seiId"),
    })
    const res = await GetAllHaveSignedContractPurchaseOrdersName(data);
    if (res.success) {
      orderList.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }

  function Signet() {
    // // 生成章
    const MYFXQ = FXQ.companySeal(DispatchForm.deliverName, 0, 0, '', '');
    let view_FQX = document.querySelector("#view_FQX");
    let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
    view_FQX.innerHTML = MYFQX;
    isSeal.value = true
  }

  //更改订单
  async function changeOrder() {
    const data = qs.stringify({
      id: DispatchForm.purchaseName
    })
    let res = await PurchaseOrdersGetInfoById(data)
    if (res.success) {
      DispatchForm.receiveName = res.data.purchaserInformation
      DispatchForm.deliverName = res.data.supplyName
      DispatchForm.orderDate = res.data.orderDate.substring(0, 10)
      DispatchForm.deliveryTime = res.data.deliveryDate.substring(0, 10)
      DispatchForm.originInfoList = res.data.purchaseDetails
      DispatchForm.infoList = JSON.parse(res.data.purchaseDetails)
      let total = 0
      //计算商品总额
      DispatchForm.infoList.forEach(item => {
        item.total = item.Price * item.Quantity
        total = total + (item.total)
      })
      DispatchForm.totalMoney = total
    }
    else {
      ElMessage.error(res.msg)
    }
  }
  //发货时间
  function changeShipTime() {
    if (!DispatchForm.purchaseName) {
      ElMessage.warning("请先选择项目")
      DispatchForm.shipDate = ''
      return
    }
    const data = new Date(DispatchForm.shipDate)
    const date1 = new Date(DispatchForm.orderDate);
    const date2 = new Date(DispatchForm.deliveryTime);
    if (data < date1) {
      ElMessage.warning("发货日期不能早于订货日期")
      DispatchForm.shipDate = ''
      return
    }
    if (data > date2) {
      ElMessage.warning("发货日期不能晚于交货日期")
      DispatchForm.shipDate = ''
      return
    }
  }
  emitter.on("Delivery", () => {
    isSeal1.value = true
  })
  emitter.on("handleTotalAmountInWords", (item) => {
    DispatchForm.totalAmountInWords = item
  })
  async function finish() {
    if (!isSeal1.value) {
      ElMessage.warning('请先在单据下盖章')
      return
    }
    if (DispatchForm.totalAmountInWords == '') {
      ElMessage.warning('请输入大写合计金额')
      return
    }
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      purchaseOrderId: DispatchForm.purchaseName,
      shippedDate: DispatchForm.shipDate + ' 00:00:00',
      consignee: DispatchForm.receiveName,
      consigner: DispatchForm.deliverName,
      haulier: DispatchForm.carrierName,
      orderDate: DispatchForm.orderDate + ' 00:00:00',
      deliveryDate: DispatchForm.deliveryTime + ' 00:00:00',
      paymentMethod: '在线支付',
      modeOfDelivery: '一次性交货',
      deliveryAddress: DispatchForm.adress,
      trackingNumber: DispatchForm.trackingNumber,
      productInformations: DispatchForm.originInfoList,
      totalAmountInWords: DispatchForm.totalAmountInWords
    }
    const res = await ProductShipmentOrdersCreate(data);
    if (res.success) {
      ElMessage.success('委托发货成功！');
      ClosePanelVisible()
      getList()
      roundAddress()
    } else {
      ElMessage.error(res.msg);
    }
  }
  function ClosePanelVisible() {
    DispatchForm.receiveName = ''
    DispatchForm.deliverName = ''
    DispatchForm.orderDate = ''
    DispatchForm.deliveryTime = ''
    DispatchForm.originInfoList = ''
    DispatchForm.infoList = ''
    DispatchForm.totalMoney = ''
    DispatchForm.purchaseName = ''
    DispatchForm.shipDate = ''
    Vdialog.value = false
    showdialog.value = false
    nextStep.value = false
    isSeal.value = false
    isSeal1.value = false
    roundAddress()
    GetDeliveryNumber()
  }

  function MaterialDetails(row) {
    if (row.isInWarehouse !== null) {
      isAccept.value = true
    } else {
      isAccept.value = false
    }
    DispatchForm.shipDate = row.shippedDate.substring(0, 10)
    DispatchForm.trackingNumber = row.trackingNumber
    DispatchForm.adress = row.deliveryAddress
    DispatchForm.receiveName = row.consignee
    DispatchForm.deliverName = row.consigner
    DispatchForm.totalAmountInWords = row.totalAmountInWords
    DispatchForm.orderDate = row.orderDate.substring(0, 10)
    DispatchForm.deliveryTime = row.deliveryDate.substring(0, 10)
    DispatchForm.originInfoList = row.productInformations
    DispatchForm.infoList = JSON.parse(row.productInformations)
    DispatchForm.purchaseName = row.purchaseName
    let total = 0
    //计算商品总额
    DispatchForm.infoList.forEach(item => {
      item.total = item.Price * item.Quantity
      total = total + (item.total)
    })
    DispatchForm.totalMoney = total
    showdialog.value = true
    nextTick(() => {
      const MYFXQ = FXQ.companySeal(row.consigner, 0, 0, '', '');
      let view_FQX = document.querySelector("#view_FQX");
      let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
      view_FQX.innerHTML = MYFQX;
      if (row.whetherShip) {
        const MYFXQ = FXQ.companySeal(DispatchForm.carrierName, 0, 0, '', '');
        let view_FQX = document.querySelector("#view_FQXSHOW");
        let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
        view_FQX.innerHTML = MYFQX;
      }
    })

  }

  function clickNextStep() {
    if (!DispatchForm.shipDate) {
      ElMessage.warning('请选择发货日期')
    }
    else if (!isSeal.value) {
      ElMessage.warning('请先完成盖章后进行下一步')
    } else {
      nextStep.value = true
    }
  }
  // 
  async function GetDeliveryNumber() {
    const res = await ProductShipmentOrdersGetShippingCode();
    if (res.success) {
      DispatchForm.trackingNumber = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }

  async function handleRecept(row) {
    selectData.value = row
    isAccept.value = true
    DispatchForm.shipDate = row.shippedDate.substring(0, 10)
    DispatchForm.trackingNumber = row.trackingNumber
    DispatchForm.adress = row.deliveryAddress
    DispatchForm.receiveName = row.consignee
    DispatchForm.deliverName = row.consigner
    DispatchForm.totalAmountInWords = row.totalAmountInWords
    DispatchForm.orderDate = row.orderDate.substring(0, 10)
    DispatchForm.deliveryTime = row.deliveryDate.substring(0, 10)
    DispatchForm.originInfoList = row.productInformations
    DispatchForm.infoList = JSON.parse(row.productInformations)
    DispatchForm.purchaseName = row.purchaseName
    let total = 0
    //计算商品总额
    DispatchForm.infoList.forEach(item => {
      item.total = item.Price * item.Quantity
      total = total + (item.total)
    })
    DispatchForm.totalMoney = total
    receptVisible.value = true
  }

  async function confirmAccept() {
    // 调修改状态接口
    const params = qs.stringify({
      id: selectData.value.purchaseOrderId,
      status: 2,
    })
    let res = await ConfirmInWarehouse(params)
    if (res.success) {
      ElMessage.success('回单确认成功！')
      receptVisible.value = false
      getList()
    } else {
      ElMessage.error(res.msg)
    }
  }
  onMounted(() => {
    getList()
    getOrderList()
    roundAddress()
    GetDeliveryNumber()
  })
  return {
    Vdialog,
    loading,
    columns,
    dataList,
    DispatchForm,
    roundAddress,
    FormDisabled,
    MaterialDetails,
    Signet,
    isSeal,
    nextStep,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    orderList,
    changeOrder,
    changeShipTime,
    clickNextStep,
    finish,
    ClosePanelVisible,
    showdialog,
    receptVisible,
    handleRecept,
    confirmAccept,
    isAccept,
  }

}
